<?php

include('../../include/functions.inc.php');
if (!isEmpty(getParam('operation'))) {
    switch (getParam('operation')) {
        case 'aiu':
            findStudent($db, 'AIU_CODE=' . getParam('AIU_CODE'));
            break;
        case 'id':
            findStudent($db, 'ID=' . getParam('ID'));
            break;
        case 's':
            save($db, $user);
            break;
        case 'stud':
            listStudents();
            break;
        case 'invoice':
            saveInvoice($db, $user);
            break;
    }
}

function listStudents() {
    header('Location: ../students/slistStudents.php');
}

function findStudent($db, $where) {
    $r = $db->query_select("cllg_student", $where);
    $datos = array();
    if (count($r) > 0) {
        $c = $r[0];
        $l = $db->query_select('cllg_account', "FK_STUDENT=" . $c['ID']);
        $ac = $l[0];
        if (count($ac) > 0) {
            $datos = array('NAME' => $c['FIRTS_NAME'] . ',' . $c['LAST_NAME'], 'ID' => $c['ID'],
                'AIU' => ($c['AIU_CODE'] != NULL) ? $ac['AIU_CODE'] : "", 'AC' => $ac['ID']);
        } else {
            $datos = array('ERROR' => 'NO TIENE CUENTA CORRIENTE EN ESTA ENTIDAD!');
        }
    } else {
        $datos = array('ERROR' => 'NO EXISTE NINGUN ESTUDIANTE CON ESE CODIGO!');
    }
    $_SESSION['pack'] = serialize($datos);
    header('Location: ../../include/transport.php');
}

function save($db, $user) {
    $student = getParam('ID');
    $rs = $db->query_select('cllg_account', 'FK_STUDENT=' . $student);
    $ac = $rs[0];

    $cbalance = $ac["CURR_BALANCE"];
    $cargos = json_decode(stripslashes(getParam('json')), TRUE);
    $total = 0;
    $penal = 0;
    $now = date("y-m-d");
    $pagos = array();

    foreach ($cargos as $c) {
        $pbalance = $cbalance;
        $fPago = NULL;
        $abono = $c["ABONO"];
        $penal = $c["PENAL"];
        $dataCargo = array(
            'TOTAL' => sqlValue($c["TOT"], 'double'),
            'TOTAL_PENDIENTE' => sqlValue(($c["TOT"] - $c["ABONO"]), 'double'));
        if ($c["ABONO"] == $c["TOT"]) { // si cancela por completo el cargo
            $fPago = sqlValue($now, 'date');
            $dataCargo['DATE_PAYED'] = $fPago;
        }
        $db->query_update('cllg_cargo', $dataCargo, "ID=" . $c["ID"]);

        $cancel = array('TYPE_CANCEL' => sqlValue(getParam("TYPE_CANCEL"), "text"),
            'COMMENT' => sqlValue(getParam("COMMENT_CANCEL"), "text"),
            'TOTAL' => $abono, "FK_ACCOUNT" => $ac["ID"],
            'CREATED' => sqlValue($now, "date"), "CREATED_BY" => sqlValue($user->name, "text"));

        $db->query_insert("cllg_cancel", $cancel);

        $cbalance+=$abono;
        $total+=$abono;
    }

    $db->query_update('cllg_account', array('CURR_BALANCE' => $cbalance,
        'PREV_BALANCE' => $pbalance), 'ID=' . $ac['ID']);
    $cy = getCycle($db, $user);
    $totalIn = $cy["MONEY_IN"] + $total;   //suma el dinero que entra
    $db->query_update("cllg_college_cycle", array("MONEY_IN" => $totalIn), "CODE=" . $user->cycle . " AND FK_ENTITY=" . $user->entity);

    header('Location: index.php');
}

function getNoFact($db, $entity) {
    $f = $db->query_select("cllg_factura_serie", "STATUS=1 AND FK_ENTITY=" . $entity);
    if (count($f) > 0) {
        return $f[0];
    }
    return null;
}

function getNextFactura($db, $serie, $entity) {
    $f = $db->queryToArray("select max(NUMERO) No FROM cllg_factura WHERE FK_ENTITY=" . $entity .
            " AND SERIE=" . sqlValue($serie, "text"));

    if (count($f) > 0 && !isEmpty($f[0]["No"])) {
        return $f[0]["No"];
    } else {
        return 0;
    }
}

function getNextIDFactura($db) {
    $f = $db->queryToArray("select max(ID) as No FROM cllg_factura");
    if (count($f) > 0 && !isEmpty($f[0]["No"])) {
        return $f[0]["No"];
    } else {
        return 1;
    }
}

function getLastAbono($db) {
    $f = $db->queryToArray("select max(ID) as No FROM cllg_abono");
    if (count($f) > 0 && !isEmpty($f[0]["No"])) {
        return $f[0]["No"];
    } else {
        return 1;
    }
}

function saveInvoice($db, $user) {
    $invoice = unserialize($_SESSION["invoice"]);
    $next = getNextFactura($db, $invoice["factura"]["SERIE"], $user->entity);
    $inicio = $invoice["factura"]["INICIO"];
    if ($next < $inicio) {
        $next = $inicio;
    }
    $next++;
    $factura = array(
        "NUMERO" => $next,
        "SERIE" => sqlValue($invoice["factura"]["SERIE"], "text"),
        "FK_STUDENT" => $invoice["idstudent"],
        "FECHA" => sqlValue(date("y-m-d"), "date"), "TOTAL" => $invoice["total"],
        "NOMBRE" => sqlValue(getParam("NAME"), "text"),
        "DIRECCION" => sqlValue(getParam("ADDRESS"), "text"),
        "NIT" => sqlValue(getParam("NIT"), "text"),
        "IVA" => sqlValue($invoice["iva"], "double"),
        "TIPO_PAGO" => sqlValue($invoice["TPAGO"], "text"),
        "SUBTOTAL" => sqlValue($invoice["total"], "double"),
        "FK_ENTITY" => $user->entity,
        "NO_BOLETA" => sqlValue($invoice["boleta"], "text"));
    $db->query_insert("cllg_factura", $factura);

    $fk = getNextIDFactura($db);
    $det = array("DESCRIPCION" => sqlValue(getParam("CONCEPTO"), "text"),
        "CANTIDAD" => 1, "SUBTOTAL" => $invoice["total"], "FK_FACTURA" => $fk);

    $db->query_insert("cllg_factura_detalle", $det);
    $invoice["id"] = $fk;
    if ($invoice["TPAGO"] == "CHEQ") {
        $cheque = $invoice["chk"];
        $cheque["FACTURA"] = $fk;
        saveCheque($db, $cheque);
    }

    //guarda relacioin factura,cargo,abono
    saveRelation($db, $invoice, $user);


    $res = array("R" => 1, "FACTURA" => $invoice["factura"]["SERIE"] . "-" . $next);
    $_SESSION['pack'] = serialize($res);
    header('Location: ../../include/transport.php');
}

function saveRelation($db, $factura, $user) {
    $pagos = $factura["pagos"];
    $idFactura = $factura["id"];
    foreach ($pagos as $pago) {
        $db->query_insert("cllg_mov_cargo", array("FK_CARGO" => $pago["CARGO"],
            "FK_FACTURA" => $idFactura,
            "FK_ABONO" => $pago["ABONO"],
            "MONTO" => $pago["MONTO"],
            "CREATED" => sqlValue(date("y-m-d"), "date"),
            "CREATED_BY" => sqlValue($user->name, "text")));
    }
}

function saveCheque($db, $valCk) {
    $cheque = array("NUMERO" => sqlValue($valCk["NUMERO"], "int"),
        "FECHA" => sqlValue(date("y-m-d"), "date"),
        "MONTO" => sqlValue($valCk["MONTO"], "double"),
        "BANCO" => sqlValue($valCk["BANCO"], "text"),
        "FK_FACURA" => sqlValue($valCk["FACTURA"], "int"));

    $db->query_insert("cllg_cheque", $cheque);
}

?>